package com.foodcommunity.service.impl;

import com.foodcommunity.common.Result;
import com.foodcommunity.dto.FoodPostDTO;
import com.foodcommunity.entity.FoodPost;
import com.foodcommunity.entity.Category;
import com.foodcommunity.mapper.CategoryMapper;
import com.foodcommunity.mapper.FoodPostMapper;
import com.foodcommunity.service.FoodPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class FoodPostServiceImpl implements FoodPostService {

    @Autowired
    private FoodPostMapper foodPostMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<FoodPostDTO> getHotPosts() {
        return foodPostMapper.selectHotPosts();
    }

    @Override
    public List<FoodPostDTO> getMorePosts(int page, int size) {
        int offset = (page - 1) * size;
        return foodPostMapper.selectMorePosts(offset, size);
    }

    @Override
    public List<FoodPost> getUserPosts(Long userId) {
        return foodPostMapper.selectByUserId(userId);
    }

    @Override
    public Result<FoodPost> getPostDetail(Long id) {
        FoodPost post = foodPostMapper.selectById(id);
        if (post == null) {
            return Result.error("文章不存在");
        }
        return Result.success(post);
    }

    @Override
    @Transactional
    public Result<FoodPost> createPost(FoodPost post) {
        int rows = foodPostMapper.insert(post);
        if (rows > 0) {
            return Result.success(post);
        }
        return Result.error("创建文章失败");
    }

    @Override
    @Transactional
    public Result<FoodPost> updatePost(FoodPost post) {
        int rows = foodPostMapper.update(post);
        if (rows > 0) {
            return Result.success(post);
        }
        return Result.error("更新文章失败");
    }

    @Override
    @Transactional
    public Result<Void> deletePost(Long id, Long userId) {
        FoodPost post = foodPostMapper.selectById(id);
        if (post == null) {
            return Result.error("文章不存在");
        }
        // 如果userId为null，表示是管理员操作，允许删除任何文章
        // 如果userId不为null，则需要检查是否是文章作者
        if (userId != null && !post.getUserId().equals(userId)) {
            return Result.error("无权删除此文章");
        }
        int rows = foodPostMapper.delete(id);
        if (rows > 0) {
            return Result.success(null);
        }
        return Result.error("删除文章失败");
    }

    @Override
    public FoodPost getPostById(Long id) {
        return foodPostMapper.selectById(id);
    }

    @Override
    @Transactional
    public void incrementViews(Long id) {
        FoodPost post = foodPostMapper.selectById(id);
        if (post != null) {
            int newViews = post.getViews() + 1;
            foodPostMapper.updateViews(id, newViews);
        }
    }
    
    @Override
    public Map<String, Object> getPostList(int page, int size, String keyword) {
        Map<String, Object> result = new HashMap<>();
        
        // 计算偏移量
        int offset = (page - 1) * size;
        
        // 获取美食日记列表
        List<FoodPostDTO> posts;
        int total;
        
        if (keyword != null && !keyword.trim().isEmpty()) {
            // 如果有关键词，则进行搜索
            posts = foodPostMapper.searchPosts(keyword, offset, size);
            total = foodPostMapper.countSearchPosts(keyword);
        } else {
            // 否则获取所有美食日记
            posts = foodPostMapper.selectAllPostsWithInfo(offset, size);
            total = foodPostMapper.count();
        }
        
        // 计算总页数
        int totalPages = (total + size - 1) / size;
        
        result.put("posts", posts);
        result.put("totalPages", totalPages);
        result.put("total", total);
        
        return result;
    }

    @Override
    @Transactional
    public Result<Integer> likePost(Long id, Long userId) {
        // 检查帖子是否存在
        FoodPost post = foodPostMapper.selectById(id);
        if (post == null) {
            return Result.error("帖子不存在");
        }
        
        // TODO: 实际应用中应该检查用户是否已经点赞过，这里简化处理
        // 增加点赞数
        int newLikes = post.getLikes() + 1;
        foodPostMapper.updateLikes(id, newLikes);
        
        return Result.success(newLikes);
    }

    @Override
    public List<FoodPostDTO> getRelatedPosts(Long id, int limit) {
        // 获取当前帖子
        FoodPost post = foodPostMapper.selectById(id);
        if (post == null) {
            return new ArrayList<>();
        }
        
        // 获取相同分类的帖子
        return foodPostMapper.selectRelatedPosts(post.getCategoryId(), id, limit);
    }

    @Override
    public List<FoodPostDTO> getPostsByCategory(String category, int page, int size, String sort) {
        // 计算偏移量
        int offset = (page - 1) * size;
        
        // 根据分类名称获取分类ID
        Long categoryId = getCategoryIdByName(category);
        if (categoryId == null) {
            return new ArrayList<>();
        }
        
        // 根据排序方式获取帖子
        switch (sort) {
            case "popular":
                return foodPostMapper.selectByCategoryOrderByLikes(categoryId, offset, size);
            case "comments":
                return foodPostMapper.selectByCategoryOrderByComments(categoryId, offset, size);
            case "latest":
            default:
                return foodPostMapper.selectByCategoryOrderByTime(categoryId, offset, size);
        }
    }
    
    @Override
    public List<FoodPostDTO> getPostsBySort(String sort, int page, int size) {
        // 计算偏移量
        int offset = (page - 1) * size;
        
        // 根据排序方式获取帖子
        switch (sort) {
            case "popular":
                return foodPostMapper.selectOrderByLikes(offset, size);
            case "comments":
                return foodPostMapper.selectOrderByComments(offset, size);
            case "latest":
            default:
                return foodPostMapper.selectOrderByTime(offset, size);
        }
    }
    
    @Override
    public int getTotalPostsCount(String category) {
        if (category != null && !category.isEmpty()) {
            // 获取分类ID
            Long categoryId = getCategoryIdByName(category);
            if (categoryId != null) {
                return foodPostMapper.countByCategory(categoryId);
            }
            return 0;
        }
        return foodPostMapper.count();
    }
    
    /**
     * 根据分类名称获取分类ID
     */
    private Long getCategoryIdByName(String categoryName) {
        // 这里应该调用categoryMapper获取分类ID
        List<Category> categories = categoryMapper.selectAll();
        for (Category category : categories) {
            if (category.getName().equals(categoryName)) {
                return category.getId();
            }
        }
        return null;
    }
}